package com.zhenmyan.secdeal.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhenmyan.secdeal.Enum.ResponseEnum;
import com.zhenmyan.secdeal.exception.GlobalException;
import com.zhenmyan.secdeal.mapper.UserMapper;
import com.zhenmyan.secdeal.pojo.User;
import com.zhenmyan.secdeal.service.UserService;
import com.zhenmyan.secdeal.utils.CookieUtil;
import com.zhenmyan.secdeal.utils.MD5Util;
import com.zhenmyan.secdeal.utils.UUIDUtil;
import com.zhenmyan.secdeal.vo.LoginRequest;
import com.zhenmyan.secdeal.vo.Response;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * description:
 *
 * @author 颜真明
 * @date 2023/5/5  14:38
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public Response doLogin(LoginRequest loginRequest, HttpServletRequest request, HttpServletResponse response) {
        String mobile = loginRequest.getMobile();
        String password = loginRequest.getPassword();
        User user = userMapper.selectById(mobile);
        if (user == null) {
            throw new GlobalException(ResponseEnum.LOGIN_ERROR);
        }

        // 判断密码是否正确
        if (!Objects.equals(MD5Util.formPassToDBPass(password, user.getSlat()), user.getPassword())) {
            throw new GlobalException(ResponseEnum.LOGIN_ERROR);
        }

        String ticket = UUIDUtil.uuid();
        // 存储session
        redisTemplate.opsForValue().set("user:"+ticket, user);
        CookieUtil.setCookie(request, response, "userTicket", ticket);

        return Response.success(ResponseEnum.SUCCESS);
    }

    @Override
    public User getUserByCookie(String userTicket, HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isEmpty(userTicket)) {
            return null;
        }
        User user = (User)redisTemplate.opsForValue().get("user:" + userTicket);
        if (null != user) {
            CookieUtil.setCookie(request, response, "userTicket", userTicket);
        }
        return user;
    }


}
